/*
 * ------------------------------------------------------------------
 * Copyright © 2017, Hangzhou  DtDream Technology Co.,Ltd. All rights reserved.
 * ------------------------------------------------------------------
 * Product : DTWare
 * Module Name : MOC
 * Date Created: 2017-08-04
 * Description :
 * ------------------------------------------------------------------
 * Modification History * DATE Name Description
 * ------------------------------------------------------------------
 * 2017-08-04 z0228 refactor project
 * ------------------------------------------------------------------
 */
/*
 * Copyright 2012-2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.gitee.booting.dspi.processor;

import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.tools.FileObject;
import javax.tools.StandardLocation;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;


/**
 * A {@code MetadataStore} is responsible for the storage of metadata on the filesystem.
 * <p>
 * Author Andy Wilkinson
 *
 * @since 1.2.2
 */
public class MetadataStore {

    private final ProcessingEnvironment environment;

    public MetadataStore(ProcessingEnvironment environment) {
        this.environment = environment;
    }

    public void writeMetadatas(List<String> metadatas) throws IOException {
        OutputStream outputStream = createMetadataResource().openOutputStream();
        outputStream.write(String.join("\n", metadatas).getBytes(StandardCharsets.UTF_8));
    }

    private FileObject createMetadataResource() throws IOException {
        final Filer filer = this.environment.getFiler();
        final FileObject old = filer.getResource(StandardLocation.CLASS_OUTPUT, "", Parser.DSPI_METADATA);
        old.delete();
        return filer.createResource(StandardLocation.CLASS_OUTPUT, "", Parser.DSPI_METADATA);
    }
}
